package server;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

/**
 * @author Y1n
 * @date 2021/11/19 14:06
 * @decs 封装response对象 需要依赖于 outputstream
 **/
public class Response {


    private OutputStream outputStream;

    public OutputStream getOutputStream() {
        return outputStream;
    }

    public void setOutputStream(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    public Response(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    /**
     * @author Y1n
     * @date 2021/11/19 14:32
     * @description 输出指定字符串
     * @param
     * @return
     */
    public void output(String content) throws IOException {
        outputStream.write(content.getBytes(StandardCharsets.UTF_8));
    }

    /**
     * @author Y1n
     * @date 2021/11/19 14:25
     * @description 根据url 获取到静态资源的绝对路径, 读取文件后 通过输出流 输出
     * @param
     * @return
     */
    public void outputHtml(String path) throws IOException {
          // 静态资源的绝对路径
          String absoluteResourcePath = StaticResourceUtil.getAbsolutePath(path);
          // 输入的静态资源文件
          File file = new File(absoluteResourcePath);
          if (file.exists() && file.isFile()){
              // 读取静态资源 输出静态资源
              StaticResourceUtil.outputStaticResource(new FileInputStream(file),outputStream);
          }else{
              // 输出404
              output(HttpPortocolUtil.getHttpHeaderFail());
          }
    }
}
